<?php

declare(strict_types=1);

namespace app\admin\service\dynamic;

use app\api\lib\SuPengJun;
use app\common\model\activity\ActivityModel;
use app\common\model\circle\CircleModel;
use app\common\model\dynamic\DynamicAudioModel;
use app\common\model\dynamic\DynamicCommentModel;
use app\common\model\dynamic\DynamicImgModel;
use app\common\model\dynamic\DynamicLikeModel;
use app\common\model\dynamic\DynamicVideoModel;
use app\common\model\order\OrderGoodsModel;
use app\common\model\order\OrderModel;
use app\common\model\system\PluginModel;
use app\common\model\user\UserModel;
use Dengje\Pxy\BaseService;

class DynamicService extends BaseService
{
    protected $model = null;


    public function __construct()
    {
        $this->model =  new \app\common\model\dynamic\DynamicModel();
    }

    public function list()
    {
        $where = [];
        $order = ['top' => 'desc', 'id' => 'desc'];
        $status = request()->get('status', 0);
        $content = request()->get('content', '');
        $id = request()->get('id', '');
        $user_id = request()->get('user_id', '');
        if ($status == 0) $order = ['status' => 'asc', 'top' => 'desc', 'id' => 'desc'];
        if ($status) $where[] = ['status', '=', $status];
        if ($user_id) $where[] = ['user_id', '=', $user_id];
        if ($id) $where[] = ['id', '=', $id];
        if ($content) $where[] = ['content', 'like', '%' . $content . '%'];
        $list = $this->model->where($where)->with('user')->order($order)->paginate(request()->get('page_size/d', 10));
        $list->map(function ($v) {
            $province = $v['province'];
            if (!$province) $province = $v['city'];
            if (!$province) $province = $v['country'];
            $v['ip_str'] = SuPengJun::addsStr($province);
            $v['like_count'] = DynamicLikeModel::where('dynamic_id', $v['id'])->count();
            $v['comment_count'] = DynamicCommentModel::where('dynamic_id', $v['id'])->count();
            // $v['comment'] = DynamicCommentModel::where('dynamic_id', $v['id'])->where('status', 0)->count();
            return $v;
        });
        return $list;
    }

    public function detail($id)
    {
        $detail = $this->model->where('id', $id)->with('user')->find();
        if ($detail['type'] == 1) {
            $detail['imgs'] = DynamicImgModel::where('dynamic_id', $detail['id'])->column('url');
            $detail['imgs_extend'] = DynamicImgModel::where('dynamic_id', $detail['id'])
                ->field('url,wide,high')->select();
        } else if ($detail['type'] == 2) {
            $detail['video'] = DynamicVideoModel::where('dynamic_id', $detail['id'])
                ->field('cover,url,wide,high')->find();
        } else if ($detail['type'] == 3) {
            $detail['audio'] = DynamicAudioModel::where('dynamic_id', $detail['id'])
                ->field('cover,url,name,intro,size')->find();
        }
        if ($detail['order_id']) {
            $detail['order_goods'] = OrderGoodsModel::where('order_id', $detail['order_id'])
                ->field('goods_name,product_img')->select();
        }
        return $detail;
    }

    public function create($request)
    {
        $data = $this->preExcludeFields($request->param());
        if ($data['type'] == 1 && empty($data['imgs_extend'])) $data['type'] = 0;
        if ($data['type'] == 2 && empty($data['video'])) $data['type'] = 0;
        if ($data['type'] == 3 && empty($data['audio'])) $data['type'] = 0;
        $model = [
            'user_id' => $data['user_id'],
            'content' => $data['content'],
            'type' => $data['type'],
            'order_id' => $data['order_id'],
            'top' => $data['top'],
            'likes' => $data['likes'],
            'browse' => $data['browse'],
            'status' => $data['status'],
            'create_time' => time(),
        ];
        if ($data['circle_id']) {
            $circle = CircleModel::where('id', $data['circle_id'])->field('id,name,avatar')->find();
            if ($circle) {
                $model['circle_id'] = $circle['id'];
                $model['circle_name'] = $circle['name'];
                $model['circle_avatar'] = $circle['avatar'];
            }
        } else {
            $model['circle_id'] = '';
            $model['circle_name'] = '';
            $model['circle_avatar'] = '';
        }
        if ($data['activity_id']) {
            $activity = ActivityModel::where('id', $data['activity_id'])->field('id,name,imgs')->find();
            if ($activity) {
                $model['activity_id'] = $activity['id'];
                $model['activity_name'] = $activity['name'];
                $model['activity_img'] = explode(',', $activity['imgs'])[0];
            }
        } else {
            $model['activity_id'] = '';
            $model['activity_name'] = '';
            $model['activity_img'] = '';
        }
        $userInfo = UserModel::where('id', $data['user_id'])->where('type', 2)->field('id,ip,country,province,city')->find();
        if ($userInfo) {
            $model['ip'] = $userInfo['ip'];
            $model['country'] = $userInfo['country'];
            $model['province'] = $userInfo['province'];
            $model['city'] = $userInfo['city'];
        } else {
            $model = SuPengJun::ipStr($model, $request->ip());
        }
        $id = $this->model->insertGetId($model);
        self::dynamic_annex($id, $data['user_id'], $data['type'], $data['imgs_extend'], $data['video'], $data['audio']);
        return $id;
    }

    public function update($request)
    {
        $data = $this->preExcludeFields($request->param());
        $id = $data['id'];
        if ($data['type'] == 1 && empty($data['imgs_extend'])) $data['type'] = 0;
        if ($data['type'] == 2 && empty($data['video'])) $data['type'] = 0;
        if ($data['type'] == 3 && empty($data['audio'])) $data['type'] = 0;
        $model = [
            'user_id' => $data['user_id'],
            'content' => $data['content'],
            'type' => $data['type'],
            'order_id' => $data['order_id'],
            'top' => $data['top'],
            'likes' => $data['likes'],
            'browse' => $data['browse'],
            'status' => $data['status'],
            'update_time' => time(),
        ];
        if ($data['circle_id']) {
            $circle = CircleModel::where('id', $data['circle_id'])->field('id,name,avatar')->find();
            if ($circle) {
                $model['circle_id'] = $circle['id'];
                $model['circle_name'] = $circle['name'];
                $model['circle_avatar'] = $circle['avatar'];
            }
        } else {
            $model['circle_id'] = '';
            $model['circle_name'] = '';
            $model['circle_avatar'] = '';
        }
        if ($data['activity_id']) {
            $activity = ActivityModel::where('id', $data['activity_id'])->field('id,name,imgs')->find();
            if ($activity) {
                $model['activity_id'] = $activity['id'];
                $model['activity_name'] = $activity['name'];
                $model['activity_img'] = explode(',', $activity['imgs'])[0];
            }
        } else {
            $model['activity_id'] = '';
            $model['activity_name'] = '';
            $model['activity_img'] = '';
        }
        $userInfo = UserModel::where('id', $data['user_id'])->where('type', 2)->field('id,ip,country,province,city')->find();
        if ($userInfo) {
            $model['ip'] = $userInfo['ip'];
            $model['country'] = $userInfo['country'];
            $model['province'] = $userInfo['province'];
            $model['city'] = $userInfo['city'];
        }
        $this->model->where('id', $id)->update($model);
        if ($data['type'] == 1) DynamicImgModel::where('dynamic_id', $id)->delete();
        if ($data['type'] == 2) DynamicVideoModel::where('dynamic_id', $id)->delete();
        if ($data['type'] == 3) DynamicAudioModel::where('dynamic_id', $id)->delete();
        self::dynamic_annex($id, $data['user_id'], $data['type'], $data['imgs_extend'], $data['video'], $data['audio']);
        return $id;
    }

    public function delete($id)
    {
        $orderId = $this->model->where('id', $id)->value('order_id');
        if ($orderId) {
            $type = OrderModel::where('id', $orderId)->value('type');
            if ($type == 9) {
                OrderModel::where('id', $orderId)->delete();
                OrderGoodsModel::where('order_id', $orderId)->delete();
            }
        }
        $this->model->where('id', $id)->delete();
        DynamicImgModel::where('dynamic_id', $id)->delete();
        DynamicVideoModel::where('dynamic_id', $id)->delete();
        DynamicAudioModel::where('dynamic_id', $id)->delete();
        DynamicLikeModel::where('dynamic_id', $id)->delete();
        DynamicCommentModel::where('dynamic_id', $id)->delete();
        return success('删除成功！');
    }

    public function comment()
    {
        $dynamicId = request()->get('dynamic_id', 0);
        $where[] = ['dynamic_id', '=', $dynamicId];
        $where[] = ['reply_comment_id', '=', 0];
        $content = request()->get('content', '');
        $id = request()->get('id', '');
        $type = request()->get('type', '');
        $user_id = request()->get('user_id', 0);
        if ($user_id) $where[] = ['user_id', '=', $user_id];
        if ($id) $where[] = ['id', '=', $id];
        if ($content) $where[] = ['content', 'like', '%' . $content . '%'];
        $list = DynamicCommentModel::where($where)->with('user')
            ->order(['status' => 'asc', 'id' => $type ? 'desc' : 'asc'])
            ->paginate(request()->get('page_size/d', 10));
        $list->map(function ($item) {
            $province = $item['province'];
            if (!$province) $province = $item['city'];
            if (!$province) $province = $item['country'];
            $item['ip_str'] = SuPengJun::addsStr($province);
            $item['visible'] = false;
            $item['children'] = DynamicCommentModel::with('user')
                ->where('reply_comment_id', $item['id'])->select();
            $item['children']->map(function ($v) {
                $province = $v['province'];
                if (!$province) $province = $v['city'];
                if (!$province) $province = $v['country'];
                $v['ip_str'] = SuPengJun::addsStr($province);
                $v['visible'] = false;
                return $v;
            });
            return $item;
        });

        return $list;
    }
    public function edit_comment($id, $data)
    {
        $data = $this->preExcludeFields($data);
        return DynamicCommentModel::where('id', $id)->update(['status' => $data['status']]);
    }
    public function del_comment($id)
    {
        $comment = DynamicCommentModel::where('reply_comment_id', $id)->count();
        if ($comment) {
            DynamicCommentModel::where('id', $id)->update(['status' => 3]);
        } else {
            DynamicCommentModel::where('id', $id)->delete();
        }
        return success('删除成功！');
    }

    public static function dynamic_annex($id = 0, $uid = 0, $type = 0, $imgs = [], $video = [], $audio = [])
    {
        if ($type == 1 && !empty($imgs)) {
            $img_model = [];
            foreach ($imgs as $k => $v) {
                $img_model[$k]['url'] = $v['url'];
                $img_model[$k]['wide'] = $v['wide'];
                $img_model[$k]['high'] = $v['high'];
                $img_model[$k]['dynamic_id'] = $id;
                $img_model[$k]['user_id'] = $uid;
            }
            (new DynamicImgModel)->insertAll($img_model);
        }
        if ($type == 2 && !empty($video)) {
            (new DynamicVideoModel())->insert([
                'url' => $video['url'],
                'cover' => $video['cover'],
                'wide' => $video['wide'],
                'high' => $video['high'],
                'dynamic_id' => $id,
                'user_id' => $uid,
                'update_time' => time()
            ]);
        }
        if ($type == 3 && !empty($audio)) {
            (new DynamicAudioModel())->insert([
                'cover' => $audio['cover'],
                'url' => $audio['url'],
                'name' => $audio['name'],
                'intro' => $audio['intro'],
                'size' => $audio['size'] ?? 1,
                'dynamic_id' => $id,
                'user_id' => $uid
            ]);
        }
    }

    public function select()
    {
        $type = request()->get('type', 0);
        $data['user'] = UserModel::where('status', 1)->where('type', 2)->field('id,name')->select();
        if ($type == 0) {
            $data['circle'] = CircleModel::where('status', 'in', [1, 2])->field('id,name')->select();
            $data['order'] = OrderModel::where('status', '<>', 6)->field('id,order_no')->select();
            $data['activity'] = ActivityModel::field('id,name')->select();
            $data['is_activity'] = PluginModel::where('name', 'activity')->value('id') ? true : false;
        } else {
            $data['dynamic'] = $this->model->where('status', 2)->field('id,content')->select();
        }
        return $data;
    }
}
